#include "Stdafx.h"
#include "Direct3DLibrary9.h"
#include "Direct3DDevice9.h"

using namespace Vortex::Wrapper::Direct3D;

Direct3DLibrary9::Direct3DLibrary9() {
	_handle = Direct3DCreate9(D3D_SDK_VERSION);
}

Direct3DLibrary9::~Direct3DLibrary9() {
	_handle->Release();
}

HResult Direct3DLibrary9::CreateDevice(int adapterOrdinal, D3DDeviceType type, IntPtr focusWindow, D3DDeviceCreateFlags flags, PresentParameters% presentParams, Direct3DDevice9^% device) {
	D3DPRESENT_PARAMETERS pp = presentParams.ToD3DPRESENT_PARAMETERS();
	
	IDirect3DDevice9* pDirect3DDevice = NULL;
	HResult hr = HResult(_handle->CreateDevice(adapterOrdinal, (D3DDEVTYPE)type, (HWND)focusWindow.ToPointer(), (DWORD)flags, &pp, &pDirect3DDevice));
	if (hr.IsSuccess) {
		device = gcnew Direct3DDevice9(pDirect3DDevice);
	} else {
		device = nullptr;
	}
	return hr;
}

///<summary>Number of adapters registered in system</summary>
UINT Direct3DLibrary9::GetAdapterCount() {
	return _handle->GetAdapterCount();
}

///<summary>Returns count of adapter modes</summary>
UINT Direct3DLibrary9::GetAdapterModeCount(UINT adapter, D3DFormat format) {
	return _handle->GetAdapterModeCount(adapter, (D3DFORMAT)format);
}

///<summary>Check can device use this enumerate adapter mode</summary>
HResult Direct3DLibrary9::EnumAdapterModes(UINT adapter, D3DFormat format, UINT mode, [Out] DisplayMode% displayMode) {
	D3DDISPLAYMODE dm;
	HResult hr = HResult(_handle->EnumAdapterModes(adapter, (D3DFORMAT)format, mode, &dm));
	displayMode = DisplayMode(&dm);
	return hr;
}

HResult Direct3DLibrary9::GetDeviceCaps(UINT Adapter, [Out] D3DCaps% caps) {
	D3DCAPS9 caps9;
	HResult hr = HResult(_handle->GetDeviceCaps(Adapter, D3DDEVTYPE_HAL, &caps9));
	caps = D3DCaps(&caps9);
	return hr;
}

HResult Direct3DLibrary9::GetAdapterIdentifier(UINT Adapter, [Out] D3DAdapterIdentifier% adapteri) {
	D3DADAPTER_IDENTIFIER9 ai;
	HResult hr = HResult(_handle->GetAdapterIdentifier(Adapter, 0, &ai));
	adapteri = D3DAdapterIdentifier(&ai);
	return hr;
}
